package com.lvmama.rhino.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtils {
	/**
	 * 将对象序列化成字符串
	 * @param obj
	 * @return
	 * @throws IOException
	 */
	public static String serialize(Object obj) throws IOException {
		if(obj == null) {
			return null;
		}
		ByteArrayOutputStream byteArrayOutputStream = null;
		ObjectOutputStream objectOutputStream = null;
		String serStr = "";
		try {
			byteArrayOutputStream = new ByteArrayOutputStream();
			objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(obj);
			serStr = byteArrayOutputStream.toString("ISO-8859-1");
			serStr = java.net.URLEncoder.encode(serStr, "UTF-8");
		} catch (IOException e) {
			throw e;
		} finally {
			if(null != objectOutputStream) {
				objectOutputStream.close();
			}
			if(null != byteArrayOutputStream) {
				byteArrayOutputStream.close();
			}
		}
		return serStr;
	}
	
	/**
	 * 反序列化，并强转成指定类型的对象
	 */
	@SuppressWarnings("unchecked")
	public static <T> T deserialize(String value, Class<T> clazz) throws Exception {
		return (T) deserialize(value);
	}
	
	/**
	 * 反序列化
	 */
	public static Object deserialize(String value) {
		ByteArrayInputStream byteArrayInputStream = null;
		ObjectInputStream objectInputStream = null;
		try {
			String redStr = java.net.URLDecoder.decode(value, "UTF-8");
			byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));
			objectInputStream = new ObjectInputStream(byteArrayInputStream);
			return objectInputStream.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(null != objectInputStream) {
				try {
					objectInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null != byteArrayInputStream) {
				try {
					byteArrayInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}
